<?php

error_reporting(E_ALL);

require_once __DIR__.'/../../lib/silex.phar';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app = new Silex\Application();

$app['debug'] = true;

// mongodb service
$app['mongo'] = $app->share(function () {
	$conn = new Mongo();
	return $conn->postik->desktop;
});

// register url generator
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());

// only for testing purpouse
$app->get('/desktops', function(Request $request) use ($app) {
    return '<form method=post><input type="submit" value="CREATE" /></form>';
});

// create a desktop
$app->post('/desktops', function(Request $request) use ($app) {
	$doc = array(
		'notes' => array(),
		'created' => new MongoDate(time())
	);
	$app['mongo']->insert($doc);
	$view = array(
		'id' => (string)$doc['_id'],
		'created' => $doc['created']
	);
    return new Response(
	    json_encode($view),
        201, // created
        array(
	        'Content-Type' => 'application/json',
	        'Location' => $app['url_generator']->generate('desktop', array('id' => $view['id']))
	    )
    );
});

// get a desktop by its id
$app->get('/desktops/{id}', function(Request $request, $id) use ($app) {
    $doc = $app['mongo']->findOne(array('_id' => new MongoId($id)));
    if ($doc === NULL)
    	return new Response(
    		NULL,
    		404, // not found
    		array(
	        	'Content-Type' => 'application/json',
		    )
	    );
	$view = array(
		'id' => (string)$doc['_id'],
		'created' => $doc['created']
	);
	return new Response(
	    json_encode($view),
        200, // ok
        array(
	        'Content-Type' => 'application/json',
	    )
    );
})
->bind('desktop');

$app->run();
